package tech.yixiyun.framework.kuafu.kits;

import tech.yixiyun.framework.kuafu.log.LOGGER;
import tech.yixiyun.framework.kuafu.shutdown.ShutdownRegistry;

import java.util.concurrent.*;

/**
 * 任务工具类，通过一个线程池执行指定的任务
 */
public class TaskKit {

    private static final ExecutorService executor ;
    private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<Runnable>();
    static {
        int threads = Runtime.getRuntime().availableProcessors();
        executor = new ThreadPoolExecutor(threads, threads,
                0L, TimeUnit.MILLISECONDS,queue
                );
    }
    static {
        ShutdownRegistry.register(() -> {
            executor.shutdown();
        });
    }

    /**
     * 执行任务
     * @param task
     */
    public static <T,R> void execute(Runnable task) {
        executor.execute(task);
    }

    /**
     * 获取当前等待的任务数量
     * @return
     */
    public static int getWaitTaskCount() {
        return queue.size();
    }


    /**
     * 关闭线程池
     */
    public static void shutdown() {
        LOGGER.info("任务线程池准备关闭");
        executor.shutdown();
    }



}
